package com.worklog.struts2.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.base.Pagination.Pagination;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.system.pojo.Dept;
import com.system.pojo.Person;
import com.system.service.IDeptService;
import com.system.service.IPersonService;
import com.system.struts2.util.PersonInfo;
import com.system.struts2.util.PersonUtil;
import com.worklog.pojo.Worklog;
import com.worklog.service.IWorklogService;

public class WorklogAction extends ActionSupport {
	private Worklog worklog;
	private IWorklogService<Worklog> worklogSer;
	public List<Worklog> worklogList = new ArrayList<Worklog>();
	public Map weekMap = new LinkedHashMap();// HashMap(){};
	private Person person;
	private IPersonService<Person> personSer;
	public List<Person> personList = new ArrayList<Person>();
	private Dept dept;
	private IDeptService<Dept> deptSer;
	public List<Dept> deptList = new ArrayList<Dept>();
	private Date date; // 日期变量
	private String week; // 星期变量
	private Pagination pagination;
	private String flag = null; // exel导出模式
	HttpServletRequest request;
	HttpServletResponse response;

	public String init() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		PersonInfo personInfo = PersonUtil.getPersonInfo(request, response);
		person = (Person) personSer.find(Person.class, personInfo.getId());
		date =this.getSystemDate();
		worklog = worklogSer.getWorklog(person, date);
		ActionContext.getContext().getSession().put("worklog", worklog);

		return "main";
	}

	public String dateView() throws Exception {
		request = ServletActionContext.getRequest();
		PersonInfo personInfo = PersonUtil.getPersonInfo(request, response);
		person = (Person) personSer.find(Person.class, personInfo.getId());
		// 获取action提交过了的日期，进行数据查询
		String time = request.getParameter("date");
		date = this.formatDate(time, "yyyy-MM-dd");
		// 根据日期和用户进行查找
		worklog = worklogSer.getWorklog(person, date);
		// 查找日期无日志记录，创建一个空日志发送到jsp页面
		if (worklog == null) {
			worklog = new Worklog();
			worklog.setDate(date);
		}
		return "dateView";
	}

	public String weekView() throws Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		PersonInfo personInfo = PersonUtil.getPersonInfo(request, response);
		// 构建weekMap
		weekMap.put("星期日", "");
		weekMap.put("星期一", "");
		weekMap.put("星期二", "");
		weekMap.put("星期三", "");
		weekMap.put("星期四", "");
		weekMap.put("星期五", "");
		weekMap.put("星期六", "");
		// 获取当前时间对应周的周一时间，为读取本周日志数据做准备
		Calendar calender = Calendar.getInstance(Locale.CHINA);
		calender.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		date = this.formatDate(calender.getTime(), "yyyy-MM-dd");
		// 根据本周周一日期查询所有大于等于周一日期的值
		String hql = "From Worklog w where w.date >= '" + date
				+ "' and w.person =" + personInfo.getId();
		worklogList = worklogSer.list(hql);

		if (worklogList.size() > 0) {
			week = this.dateToWeek(worklogList.get(0).getDate());
			for (int i = 0; i < worklogList.size(); i++) {
				week = this.dateToWeek(worklogList.get(i).getDate());
				// 遍历weekMap ,将数据库存储的值与weekMap中的星期做对比，存入相应位置
				Iterator it = weekMap.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry pairs = (Map.Entry) it.next();
					if (pairs.getKey().equals(week))
						weekMap.put(week, worklogList.get(i).getContent());
				}
			}
		}
		return "weekView";
	}

	public String dateToWeek(Date date) {
		Calendar calender = Calendar.getInstance(Locale.CHINA);
		calender.setTime(date);
		SimpleDateFormat df = new SimpleDateFormat("EEE");
		week = df.format(calender.getTime());
		return week;
	}

	public String monthView() throws Exception {
		Calendar calender = Calendar.getInstance(Locale.CHINA);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");

		// 获取登陆用户信息
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		PersonInfo personInfo = PersonUtil.getPersonInfo(request, response);
		// 根据用户id 查找该用户的日志数据量
		int totalCount = worklogSer.getTotalCount(
				" select count(w) from Worklog w " + " where w.person = "
						+ personInfo.getId(), null);
		// 生成分页工具条
		pagination = new Pagination(request, response);
		pagination.setRecordCount(totalCount);
		String nowDate = request.getParameter("nowDate");
		String id = request.getParameter("siteid");

		if (id != null && nowDate != null) {
			date = df.parse(nowDate);
			calender.setTime(date);
			// System.out.println("The YEAR is: " +
			// calender.get(Calendar.YEAR));
			int year = calender.get(Calendar.YEAR);
			int month = calender.get(Calendar.MONTH) + 1;
			if (id.equals("-y")) {
				year = year - 1;
			} else if (id.equals("-m")) {
				month = month - 1;
			} else if (id.equals("m")) {
				month = month + 1;
			} else if (id.equals("y")) {
				year = year + 1;
			}
			date = df.parse(year + "-" + month);
			// System.out.println("The YEAR is: " + date);
		} else {
			date = this.formatDate(calender.getTime(), "yyyy-MM-dd");
		}

		String hql = "From Worklog w where w.date like '%" + df.format(date)
				+ "%' and w.person =" + personInfo.getId();
		worklogList = worklogSer.list(hql);
		return "monthView";
	}

	public String list() throws Exception {

		personList = personSer.list("from Person");
		deptList = deptSer.list("from Dept");

		// 获取登陆用户信息
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		PersonInfo personInfo = PersonUtil.getPersonInfo(request, response);
		// 根据用户id 查找该用户的日志数据量
		int totalCount = worklogSer.getTotalCount(
				" select count(w) from Worklog w " + " where w.person = "
						+ personInfo.getId(), null);
		// 生成分页工具条
		pagination = new Pagination(request, response);
		pagination.setRecordCount(totalCount);

		String startTime = null;
		Date endTime = null;
		if (worklog != null && worklog.getDate() != null) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			startTime = df.format(worklog.getDate());
		}
		int count = 0;
		if (date != null)
			endTime = this.formatDate(date, "yyyy-MM-dd");
		StringBuffer sqlBuffer = new StringBuffer("from Worklog as a");

		if (personInfo.getGroup().equals("user")) {
			sqlBuffer.append(" where a.person =" + personInfo.getId());
			count = count + 1;
		} else {
			if ((dept != null && dept.getId() != 0)
					|| (person != null && person.getId() != 0))
			  {
				if (person.getId() != 0 && dept.getId() == 0) {
					sqlBuffer.append(" where a.person =" + person.getId());
					count = count + 1;
				} else if (dept.getId() != 0 && person.getId() == 0) {
					sqlBuffer.append(" where a.person.dept =" + dept.getId());
					count = count + 1;
				} else if (dept.getId() != 0 && person.getId() != 0) {
					sqlBuffer.append(" where a.person = " + person.getId()
							+ " and a.person.dept =" + dept.getId());
					count = count + 1;
				}
			}
		}
		if (startTime != null && (endTime == null)) {
			if(count!=0)
			   sqlBuffer.append(" and a.date >='" + startTime + "'");
			else
				{
				 sqlBuffer.append(" where  a.date >='" + startTime + "'");
				}
		}
		if (endTime != null && (startTime == null)) {
			if(count!=0)
			  sqlBuffer.append(" and a.date <='" + endTime + "'");
			else
			{
				sqlBuffer.append(" where a.date <='" + endTime + "'");
			}
		}
		if (startTime != null && endTime != null) {
			if(count!=0)
			 sqlBuffer.append(" and a.date between '" + startTime
					+ "' and '" + endTime + "'");
			else
				sqlBuffer.append(" where a.date between '" + startTime
						+ "' and '" + endTime + "'");
		}
		worklogList = worklogSer.list(sqlBuffer.toString(), pagination
				.getFirstResult(), pagination.getPageSize(), null);

		return "list";
	}

	public String gettask() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		worklog = (Worklog) session.getAttribute("worklog");
		return "dailyView";
	}

	public String save() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		PersonInfo personInfo = PersonUtil.getPersonInfo(request, response);
		person = (Person) personSer.find(Person.class, personInfo.getId());

		date = this.getSystemDate();

		if (worklog.getDate() == null) {
			worklog.setDate(date);
		} else {
			worklog.setDate(this.formatDate(worklog.getDate(), "yyyy-MM-dd"));
		}
	//	worklog.setContent(request.getParameter("content"));
		worklog.setPerson(person);
		worklog.setDept(person.getDept());
		worklog.setPersonName(person.getName());
		worklogSer.create(worklog);
		addActionMessage("保存成功！");
		return "dailyView";
	}

	public String excelExport() throws Exception {
		StringBuffer sqlBuffer = null;
		deptList = deptSer.list("from Dept");
		if (dept != null) {
			sqlBuffer = new StringBuffer("from Worklog as w where w.date =' "
					+ this.getSystemDate() + "'");
			if (dept.getId() != 0)
				sqlBuffer.append(" and w.dept =" + dept.getId());
			dept = deptSer.find(Dept.class, dept.getId());
			flag = "exportDaily";
		} else if (worklog != null) {
			String startTime = null;
			Date endTime = null;
			if (worklog != null && worklog.getDate() != null) {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				startTime = df.format(worklog.getDate());
			}
			int count = 0;
			if (date != null)
				endTime = this.formatDate(date, "yyyy-MM-dd");
			sqlBuffer = new StringBuffer("from Worklog as a");
			if (startTime != null || endTime != null) {
				if (startTime != null && (endTime == null)) {
					if (count != 0)
						sqlBuffer.append(" and a.date >='" + startTime + "'");
					else {
						sqlBuffer
								.append(" where  a.date >='" + startTime + "'");
					}
				}
				if (endTime != null && (startTime == null)) {
					if (count != 0)
						sqlBuffer.append(" and a.date <='" + endTime + "'");
					else {
						sqlBuffer.append(" where a.date <='" + endTime + "'");
					}
				}
				if (startTime != null && endTime != null) {
					if (count != 0)
						sqlBuffer.append(" and a.date between '" + startTime
								+ "' and '" + endTime + "'");
					else
						sqlBuffer.append(" where a.date between '" + startTime
								+ "' and '" + endTime + "'");
				}
			}
			sqlBuffer.append(" order by a.date desc");
			flag = "exportTime";
		} else
			return "excelExport";
		worklogList = worklogSer.list(sqlBuffer.toString(), 0,
				Integer.MAX_VALUE, null);
		if (flag.equals("exportDaily"))
			return "export";
		else
			return "export";

	}

	 public String dailyView()
	 {
	    request = ServletActionContext.getRequest();
	    response = ServletActionContext.getResponse();
	    PersonInfo personInfo = PersonUtil.getPersonInfo(request, response);
		person = (Person) personSer.find(Person.class, personInfo.getId());
		date =this.getSystemDate();
		worklog = worklogSer.getWorklog(person, date);
			 
	 return "dailyView";
	 }

	public Date getSystemDate() {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String time = df.format(new Date());
		date = java.sql.Date.valueOf(time);
		return date;
	}

	public Date formatDate(String dateStr, String format) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat(format);

		date = df.parse(dateStr);
		String temp = df.format(date);
		date = java.sql.Date.valueOf(temp);
		return date;
	}

	public Date formatDate(Date dateStr, String formate) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat(formate);
		String temp = df.format(dateStr);
		date = java.sql.Date.valueOf(temp);
		return date;
	}

	public Worklog getWorklog() {
		return worklog;
	}

	public void setWorklog(Worklog worklog) {
		this.worklog = worklog;
	}

	public List<Worklog> getWorklogList() {
		return worklogList;
	}

	public void setWorklogList(List<Worklog> worklogList) {
		this.worklogList = worklogList;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public List<Person> getPersonList() {
		return personList;
	}

	public void setPersonList(List<Person> personList) {
		this.personList = personList;
	}

	public Dept getDept() {
		return dept;
	}

	public void setDept(Dept dept) {
		this.dept = dept;
	}

	public void setWorklogSer(IWorklogService<Worklog> worklogSer) {
		this.worklogSer = worklogSer;
	}

	public void setPersonSer(IPersonService<Person> personSer) {
		this.personSer = personSer;
	}

	public IDeptService<Dept> getDeptSer() {
		return deptSer;
	}

	public void setDeptSer(IDeptService<Dept> deptSer) {
		this.deptSer = deptSer;
	}

	public List<Dept> getDeptList() {
		return deptList;
	}

	public void setDeptList(List<Dept> deptList) {
		this.deptList = deptList;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getWeek() {
		return week;
	}

	public void setWeek(String week) {
		this.week = week;
	}

	public Map getWeekMap() {
		return weekMap;
	}

	public void setWeekMap(Map weekMap) {
		this.weekMap = weekMap;
	}

	public Pagination getPagination() {
		return pagination;
	}

	public void setPagination(Pagination pagination) {
		this.pagination = pagination;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

}
